package org.example.c_0_002;

import org.junit.Test;

/**
 * volatile 禁止指令重排序。没法演示。
 * 但是要在单例属性上加 volatile
 */
public class T_Volatile_Sort {
    private static volatile T_Volatile_Sort volatileSort;
    private int a;

    private T_Volatile_Sort(int a) {
        this.a = a;
    }

    @Override
    public String toString() {
        return "T_Volatile_Sort{" +
                "a=" + a +
                '}';
    }

    public static T_Volatile_Sort getInstance(){
        if (volatileSort == null){
            synchronized(T_Volatile_Sort.class){
                if (volatileSort == null){
                    volatileSort = new T_Volatile_Sort(10);
                }
            }
        }
        return volatileSort;
    }

    public static void main(String[] args){
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> {
                System.out.println(T_Volatile_Sort.getInstance());
            });
            thread.start();
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
